﻿using Core.Domain.Entities;
using Finbuckle.MultiTenant;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Infrastructure.Persistence.Configurations;

public class OrganizationConfiguration : IEntityTypeConfiguration<Organization>
{
    public void Configure(EntityTypeBuilder<Organization> builder)
    {
        builder
            .ToTable("Organizations", "identity")
            .IsMultiTenant();

        // 1. 主键
        builder.HasKey(u => u.Id);

        builder.Property(o => o.Name)
              .IsRequired(false)
              .HasMaxLength(100);

        builder.Property(o => o.Code)
            .IsRequired(false)
            .HasMaxLength(100);

        builder.Property(o => o.ParentId)
               .IsRequired(false);

        // 自引用关系：Parent ←→ Children
        builder.HasOne(o => o.Parent)                    // 当前组织的父级
               .WithMany()
               .HasForeignKey(o => o.ParentId)
               .OnDelete(DeleteBehavior.Restrict);

        builder.HasMany(u => u.UserOrganizations)
            .WithOne()
            .HasForeignKey(uo => uo.OrganizationId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(o => o.ParentId);
    }
}
